# coding=utf-8

import smtplib
import time, os
from configparser import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from three_robot.robot.services.tools import *
from three_robot.robot.services.tools import pro_path
from three_robot.robot.services.testplan import TestPlan


class RobotCI:
    def __init__(self):
        try:
            # 读取配置文件
            self.cfg = ConfigParser()
            self.cfg.read(pro_path('three_robot') + '/conf.ini', encoding="utf-8")
            # 目录节点
            self.ostype = self.cfg.get('ci', 'ostype')
            self.code = self.cfg.get('ci', 'codedir')
            self.wardir = self.cfg.get('ci', 'wardir')
            self.tomcatdir = self.cfg.get('ci', 'tomcatdir')
            self.winrardir = self.cfg.get('ci', 'winrardir')
            self.reportdir = self.cfg.get('ci', 'reportdir')
            self.testcasedir = self.cfg.get('ci', 'testcasedir')
            # db节点
            self.host = self.cfg.get('db', 'host')
            self.port = self.cfg.get('db', 'port')
            self.username = self.cfg.get('db', 'username')
            self.pwd = self.cfg.get('db', 'password')
            self.database = self.cfg.get('db', 'database')
            # email节点
            self.sender = self.cfg.get('email', 'sender')
            self.receivers = self.cfg.get('email', 'receivers')
            self.body = self.cfg.get('email', 'bodydir')
        except Exception as e:
            print(f'配置文件错误！导致对象实例化失败！Error:{e}')

    # 发布war到指定的tomcat的webapps
    def deploy(self):
        try:

            # # 停止tomcat
            os.system(f'{self.tomcatdir}\\bin\\shutdown.bat')
            # #删除老版本的war包和目录
            os.system(f'del /S /Q {self.tomcatdir}\\webapps\\woniusales.war')
            # # time.sleep(1)
            os.system(f'rmdir /S /Q {self.tomcatdir}\\webapps\\woniusales')
            # #将新版本复制到tomcat的webapps下
            os.system(f'copy {self.wardir} D:\\Tomcat\\tomcat8\\webapps\\woniusales.war')
            # #启动tomcat
            os.system(f'{self.tomcatdir}\\bin\\startup.bat')
            time.sleep(20)
            # # 修改配置文件
            self.db()
            # #重启tomcat
            os.system(f'{self.tomcatdir}\\bin\\shutdown.bat')
            os.system(f'{self.tomcatdir}\\bin\\startup.bat')
            time.sleep(20)
        except Exception as e:
            print(f'配置文件发生未知错误！Error:{e}')

    # if __name__ == '__main__':
    #         a = RobotCI()
    #         a.deploy()
    #         # a.email()
    #         # a.rar()
    #         # a.db()
    #         # print(time.strftime('%y-%m-%d %H:%M:%S'))

    # 修改db.properties配置文件
    def db(self, db_path='\webapps\woniusales\WEB-INF\classes\db.properties'):
        try:
            db = f'db_url=jdbc:mysql://{self.host}:{self.port}/{self.database}?useUnicode=true&characterEncoding=utf8\n' \
                 f'db_username={self.username}\n' \
                 f'db_password={self.pwd}\n' \
                 f'db_driver=com.mysql.jdbc.Driver\n'
            with open(rf'{self.tomcatdir}{db_path}', 'w') as f:
                f.write(db)
        except Exception as e:
            print(f'修改配置文件时发生错误：Error:{e}')

    # 执行测试脚本
    def run_test(self):
        # try:
        testplay = TestPlan(self.testcasedir, self.reportdir)
        testplay.runner()

    # except Exception as e:
    # print(f'配置文件发生未知错误！Error:{e}')
    # time.sleep(30)
    # self.rar()
    # self.email()

    # 压缩测试报告
    def rar(self):
        try:
            current = os.path.abspath('.')  # 获取当前绝对路径
            repot = os.path.abspath(f'{self.body}')  # 测试报告的路径
            # print(repot)
            os.system(rf'"{self.winrardir}" a {current}/repot.rar {repot}')  # 压缩报告并存放到指定位置
            print('success')
        except Exception as e:
            print(f'压缩测试报告失败！ Error:{e}')

    # 邮件发送
    def email(self, attach='./repot.rar'):
        try:
            with open(self.body, 'r', encoding='utf-8') as f:
                body = f.read()
            sender = f'{self.sender}'  # 发出邮箱
            receivers = f'{self.receivers}'  # 接收邮箱

            msg = MIMEMultipart()
            msg['Subject'] = 'woniusales持续集成报告'
            msg['From'] = sender
            msg['To'] = receivers

            content = MIMEText(body, 'html', 'utf-8')
            msg.attach(content)

            attachment = MIMEApplication(open(attach, 'rb').read())
            attachment.add_header('Content-Disposition', 'attachment', filename='report.rar')
            msg.attach(attachment)

            smtpObj = smtplib.SMTP()
            smtpObj.connect('smtp.qq.com', 25)
            smtpObj.login(user=f'{sender}', password='ztqsylftnnhmcadg')
            smtpObj.sendmail(sender, receivers, str(msg))
            smtpObj.quit()
            print(f'邮件发送成功。{time.strftime("%y-%m-%d %H:%M:%S")}')
        except smtplib.SMTPException:
            print('Error:无法发送邮件！')
        except Exception as e:
            print(f'似乎没有配置邮箱号！Error:{e}')
        finally:
            try:
                open(attach, 'rb').close()
            except Exception as e:
                print(e)

        # print('Error:无法发送邮件！')

    def start(self):
        # self.deploy()
        self.run_test()
        # time.sleep(3)
        # self.rar()
        # time.sleep(3)
        # self.email()

    # 无人值守运行框架
    def task(self):
        # while True:
        # if time.strftime('%H') == '18':
        self.start()
        # time.sleep(3601)

# if __name__ == '__main__':
#     a=RobotCI()
#     a.deploy()
#     # a.email()
#     # a.rar()
#     # a.db()
#     print(time.strftime('%y-%m-%d %H:%M:%S'))
